package com.sanjiahantang.youjiarole.module.common.presenters;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.module.city.views.impl.CityActivity;
import com.sanjiahantang.youjiarole.module.common.adapters.HomeAdapter;
import com.sanjiahantang.youjiarole.module.common.beans.HomeBean;
import com.sanjiahantang.youjiarole.module.common.beans.StringBean;
import com.sanjiahantang.youjiarole.module.common.models.IHomeModel;
import com.sanjiahantang.youjiarole.module.common.models.impl.HomeModel;
import com.sanjiahantang.youjiarole.module.common.views.HomeView;
import com.sanjiahantang.youjiarole.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiarole.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiarole.module.match.beans.MatchListBean;
import com.zbar.lib.CaptureActivity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zy on 2017/9/1.
 */

public class HomePresenter extends BaseMvpPresenter<HomeView> {

    public static final String TAG = HomePresenter.class.getName();
    private boolean isFreshing;
    private List<MatchListBean.Detail> moreList;
    private HomeAdapter adapter;
    private RecyclerView.OnScrollListener scrollListener;
    private IHomeModel homeModel;
    private int pageCount;
    private HomeBean.Data homePageData;
    //定位
    public AMapLocationClientOption mLocationOption;
    private AMapLocationClient mLocationClient;

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public HomePresenter(){
        homeModel = new HomeModel();
    }

    public void init(Context context){
        initScroller();
    }



    private void initScroller() {
        scrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                boolean isBootom = recyclerView.canScrollVertically(1);
                long current = System.currentTimeMillis();
                if (!isBootom && (System.currentTimeMillis() - current == 0)) {
                    int page = getPageCount();
                    setPageCount(page + 1);
                    mView.getMoreHomePage();
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        };
    }
    public void onLayoutRefresh(final Context context) {
        if (isFreshing) {
            return;
        } else {
            isFreshing = true;
            mView.setLayoutRefreshing(true);
            loadData(context);
        }
    }

    public void loadData(Context context){
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(context)) {
            mView.onNetError(true);
            return;
        }else{
            mView.onNetError(false);
        }
        setPageCount(1);
        homeModel.getHomePageData(context,new PageCallBack());
    }






    public void getMoreHomePage(Context context) {
        Map<String, String> param = new HashMap<>();
        param.put("page", String.valueOf(pageCount));
        homeModel.getMoreHomePageData(context,param,new MoreCallBack());
    }





    public RecyclerView.OnScrollListener getScrollerListener() {
        return scrollListener;
    }

    public void openScanner(Activity context, Fragment fragment) {
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(context)) {
            return;
        }
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            fragment.requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);

        } else {
            Intent itCapture = new Intent(context, CaptureActivity.class);
            context.startActivityForResult(itCapture, BaseView.INTENT_SCAN);

        }
    }

    public void selectArea(Activity activity) {
        Intent it = new Intent(activity,CityActivity.class);
        activity.startActivityForResult(it, BaseView.INTENT_CITY);
    }

    public void onRequestPermissionsResult(Context context,int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent itCapture = new Intent(context, CaptureActivity.class);
                context.startActivity(itCapture);
            } else {
                mView.showToast("权限被禁止，相关功能无法使用");
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)
        {
            case BaseView.INTENT_SCAN:
                onScanPageResult(resultCode,data);
                break;
        }
    }

    public void onScanPageResult(int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_OK){
            StringBean flag = (StringBean) data.getSerializableExtra(BaseView.TAG_DESIGNER_BIND);
            mView.showDialog(flag.getCode() == RESPONSE_CODE_SUC,flag.getMessage());
        }
    }

    private class PageCallBack implements CallBack<HomeBean> {

        @Override
        public void onSuccess(HomeBean response, Context context, Object tag) {
            hideProgress();
            if(response!=null && mView != null)
            {
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    mView.setLayoutRefreshing(false);
                    isFreshing = false;
                    homePageData = response.getData();
                    adapter = new HomeAdapter(context, homePageData, (MainActivity) context);
                    mView.initRecyclerView(adapter);

                } else {
                    Log.d(TAG, "response: " + response);
                }
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }

    private void hideProgress() {
        if (mView != null){
            mView.hideProgress();
        }

    }

    private class MoreCallBack implements CallBack<MatchListBean>{

        @Override
        public void onSuccess(MatchListBean response, Context context, Object tag) {
            mView.setLayoutRefreshing(false);
            if (response.getCode() == RESPONSE_CODE_SUC) {
                moreList = response.getData().getList();
                if(homePageData.getMatches() != null){
                    homePageData.getMatches().addAll(moreList);
                    adapter.notifyDataSetChanged();
                }else {
                    mView.showToast("已经到底了！");
                }

            } else if (response.getCode() == RESPONSE_CODE_FAIL) {
                mView.showToast("已经到底了！");
            } else {
                String msg = response.getMessage().toString();
                if (TextUtils.isEmpty(msg)) {

                } else
                    mView.showToast(response.getMessage().toString());
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }
}
